package com.bs.manager05.utils.interceptor;

import com.bs.manager05.entity.User;
import com.bs.manager05.utils.auth.Auth;
import com.bs.manager05.utils.exception.NoAuthException;
import com.bs.manager05.utils.exception.NoUserException;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

/**
 * @author 小姚
 * @pakeageName:com.bs.manager05.utils.interceptor
 * @ClassName:MyInterceptor
 * @Descirption:
 * @data 2022/12/18 20:48
 */
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        //判断当前是不是一个方法，如果不是，直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod=(HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        Auth auth = method.getDeclaredAnnotation(Auth.class);
        //判断有没有权限这个注解
        if(auth!=null){
            //判断用户是否登录
            User user =(User) session.getAttribute("user");
             if (user!=null){
                //获取该用户登录的访问权限
                 String value = auth.value();
                 if(user.getPremission().contains(value)){
                      return true;
                 }else{
                     throw new NoAuthException("该用户没有菜单权限");
                 }
             }else{
               throw new NoUserException("该用户信息不存在");
             }
        }else {
            return true;
        }

    }
}
